package com.edu.buservice.util.model;

import cn.dev33.satoken.stp.StpUtil;

/**
 * @program: KQAIA
 * @description:
 * @author: 无恙
 * @create: 2025-03-06 23:55
 **/


public class TenantUtil {

	private static final String TENANT_KEY = "TENANT_CTX";

	private static final ThreadLocal<TenantContext> CONTEXT_HOLDER = new InheritableThreadLocal<>();


	// 禁止实例化
	private TenantUtil() {
	}


	/**
	 * 初始化租户上下文（通常在登录时调用）
	 */
	public static void init(TenantContext tenantContext) {
		StpUtil.getTokenSession().set(TENANT_KEY, tenantContext);
		CONTEXT_HOLDER.set(tenantContext);
	}

	public static void clear() {
		CONTEXT_HOLDER.remove();
	}

	/**
	 * 获取当前租户ID
	 */
	public static String getTenantId() {
		TenantContext tenantContext = CONTEXT_HOLDER.get();
		if (tenantContext == null) {
			return null;
		}
		return tenantContext.getTenantId();
	}

	public static String getUserId() {
		TenantContext tenantContext = CONTEXT_HOLDER.get();
		if (tenantContext == null) {
			return null;
		}
		return tenantContext.getUserId();
	}

	/**
	 * 设置当前租户ID
	 */
	public static void setCurrentTenantId(String tenantId) {
		TenantContext tenantContext = CONTEXT_HOLDER.get();
		if (tenantContext == null) {
			tenantContext = new TenantContext();
			CONTEXT_HOLDER.set(tenantContext);
		}
		tenantContext.setTenantId(tenantId);
	}

	public static void setCurrentUserId(String userId) {
		TenantContext tenantContext = CONTEXT_HOLDER.get();
		if (tenantContext == null) {
			tenantContext = new TenantContext();
			CONTEXT_HOLDER.set(tenantContext);
		}
		tenantContext.setUserId(userId);
	}

	//获取当前租户信息
	public static TenantContext getTenantContext() {
		TenantContext tenantContext = CONTEXT_HOLDER.get();
		if (tenantContext == null) {
			tenantContext = new TenantContext();
			CONTEXT_HOLDER.set(tenantContext);
		}
		return tenantContext;
	}

	//获取当前用户
	public static UserInfoDTO getUserInfo() {
		TenantContext tenantContext = getTenantContext();
		return tenantContext.getUserInfo();
	}



}
